/*
 * Datart
 * <p>
 * Copyright 2021
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package datart.server.job;

import datart.core.common.Application;
import datart.core.common.FileUtils;
import datart.server.base.dto.JobFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WeChartJob extends ScheduleJob {

    public WeChartJob() {
    }

    @Override
    public void doSend() throws Exception {

        if (CollectionUtils.isEmpty(attachments)) {
            return;
        }

        String webHookUrl = jobConfig.getWebHookUrl();
        RestTemplate restTemplate = new RestTemplate();
        for (JobFile jobFile : attachments) {
            restTemplate.postForEntity(webHookUrl, webHookUrl.contains("oapi.dingtalk.com") ? createDingTalkParam(jobFile.getFile()) : createParam(jobFile.getFile()), Object.class);
        }
    }

    private Map<String, Object> createParam(File file) throws Exception {
        byte[] bytes = Files.readAllBytes(file.toPath());
        String base64 = Base64Utils.encodeToString(bytes);
        String md5 = DigestUtils.md5DigestAsHex(bytes);
        HashMap<String, Object> param = new HashMap<>();
        param.put("msgtype", "image");
        HashMap<String, String> image = new HashMap<>();
        image.put("base64", base64);
        image.put("md5", md5);
        param.put("image", image);
        return param;
    }

    private static Map<String, Object> createDingTalkParam(File file) {
        try {
            cacheFile(file);
        } catch (Exception e) {
            log.error("can't send dingTalk for cache file error,", e);
        }
        String url = Application.getProperty("datart.server.address") + Application.getProperty("datart.server.path-prefix") + "/shares/viewImage/" + file.getName();
        log.info("分享图片地址：" + url);
        HashMap<String, Object> param = new HashMap<>();
        param.put("msgtype", "markdown");
        HashMap<String, String> markdown = new HashMap<>();
        markdown.put("title", "图片消息");
        markdown.put("text", String.format("![image](%s)", url));
        param.put("markdown", markdown);
        return param;
    }

    private static void cacheFile(File file) throws IOException {
        // 确保缓存目录存在
        String cacheDir = FileUtils.concatPath(Application.getFileBasePath(), "cache", "images");
        File cacheDirectory = new File(cacheDir);
        if (!cacheDirectory.exists() && !cacheDirectory.mkdirs() && !cacheDirectory.isDirectory()) {
            // 处理创建失败的情况
            System.err.println("Failed to create directory: " + cacheDir);
        } else {
            // 成功创建或者已经存在
            System.out.println("Directory created successfully or already exists.");
        }

        // 构建目标文件路径
        File targetFile = new File(cacheDir, file.getName());

        // 检查是否需要复制文件
        if (!file.equals(targetFile)) {
            try {
                // 使用Files.copy来复制文件
                Files.copy(file.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                // 处理复制过程中的异常
                System.err.println("Failed to copy file: " + e.getMessage());
                throw e;
            }
        }
    }
}